<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\WithdrawAction\ConfirmWithdraw;
use App\Admin\Actions\WithdrawAction\RefuseWithdraw;
use Carbon\Carbon;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use App\Models\Withdraw;
use Illuminate\Http\Request;
use App\Exports\WithdrawExport;
use App\Imports\WithdrawImport;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use App\Supports\Withdraw\Withdrawer;
use App\Admin\Tools\WithdrawExportTool;
use App\Admin\Tools\WithdrawImportTool;
use Encore\Admin\Controllers\AdminController;
use App\Admin\Actions\WithdrawAction\BatchRefuse;
use App\Admin\Actions\WithdrawAction\BatchConfirm;
use App\Admin\Actions\WithdrawAction\ReturnFailedWithdraw;
use App\Exports\MyBankWithdrawExport;
use App\Services\ApplyGoldCoinWithdraw\RefuseGoldCoinWithdraw;
use App\Services\ApplyGoldCoinWithdraw\ApproveGoldCoinWithdraw;

class WithdrawsController extends AdminController
{
    protected $title = '会员提现管理';

	protected function withdraw($id = null)
	{
		if ($id and ($withdraw = Withdraw::find($id))) {
			return $withdraw;
		}
		return null;
	}

    protected function grid()
    {
        $grid = new Grid(new Withdraw());
	    $grid->model()->orderByDesc('id');

	    if ($userId = request('user_id')) {
		    $grid->model()->where('user_id', $userId)->orderByDesc('id');
	    }

        $grid->column('id', 'ID');
        $grid->column('user', '会员')->display(function () {
	        return $this->user->nameText(true);
        });
        $grid->column('paid_no', '支付宝/银行单号');
        $grid->column('method', '提现方式')
	        ->display(function ($value) {
	        	return config("site.withdraw.methods.$value");
	        });
        $grid->column('created_at', '申请时间')->display(function () {
	        return $this->created_at->toDatetimeString();
        });
	    $grid->column('alipay_user_id', '支付宝ID')->display(function ($value) {

		    if ($this->method != 'alipay') return '';

		    $bindId = $this->user->alipay_user_id;
		    $lastId = $currentId = "";
		    $last = $this->user->withdraws()->whereNotNull('paid_at')->orderByDesc('id')->first();
		    if ($last and $last->alipay_user_id) {
			    $lastId = $last->alipay_user_id;
		    }
		    $currentId = $value;
		    return "绑定：{$bindId}<br>上次：{$lastId}<br>本次：{$currentId}";

	    });
	    $grid->column('charge_amount', '服务费');
	    $grid->column('actual_amount', '实际到账');
	    $grid->column('target_amount', '提现金额');
	    $grid->column('number', '校验')->display(function () {
		    $goldCharge = route('admin.gold-charges.index', ['user_id' => $this->user_id]);
		    $goldCoin = route('admin.gold-coins.index', ['user_id' => $this->user_id]);
		    $goldBean = route('admin.gold-beans.index', ['user_id' => $this->user_id]);
		    $goldRecord = route('admin.gold-records.index', ['user_id' => $this->user_id]);

		    $goldChargesCount = $this->user->goldCharges()->whereNotNull('paid_at')->count();
		    $goldChargesSum = $this->user->goldCharges()->whereNotNull('paid_at')->sum('total_amount');
		    $goldCoinsSum = $this->user->goldCoins()->sum('money');
		    $goldBeansSum = $this->user->goldBeans()->sum('money');
		    $goldRecordCount = $this->user->goldRecords()->whereNotNull('paid_at')->count();
		    $goldRecordSum = $this->user->goldRecords()->whereNotNull('paid_at')->sum('pay_net_price');

		    $goldCharge = "<a href='{$goldCharge}'>充值校验({$goldChargesCount}/{$goldChargesSum})</a>";
		    $goldCoin = "<a href='{$goldCoin}'>余额校验({$goldCoinsSum})</a>";
		    $goldBean = "<a href='{$goldBean}'>金豆校验({$goldBeansSum})</a>";
		    $goldRecord = "<a href='{$goldRecord}'>抢购校验({$goldRecordCount}/{$goldRecordSum})</a>";

		    return "{$goldCharge}<br>{$goldCoin}<br>{$goldBean}<br>{$goldRecord}";
	    });
	    $grid->column('status', '提现状态')
		    ->display(function ($value) {
			    if ($value === 'pending') {
			    	return _label('等待处理', 'default');
			    } elseif ($value === 'refusal') {
			    	return _label('拒绝提现', 'danger');
			    } elseif ($value === 'confirmed') {
			    	return _label('审核通过', 'success');
			    } elseif ($value === 'paid') {
			    	return _label('提现到账', 'primary');
			    } elseif ($value === 'failed') {
			    	return _label('提现失败', 'warning');
			    } elseif ($value === 'returned') {
			    	return _label('提现回退', 'info');
			    } else {
			    	return '';
			    }
		    });

        $grid->disableBatchActions();
	    $grid->disableCreateButton();
	    $grid->disableColumnSelector();
	    $grid->disableExport();

	    $this->gridFilter($grid);
	    $this->gridActions($grid);
	    $this->gridTools($grid);

	    $grid->paginate(25);

        return $grid;
    }


     protected function gridTools(Grid $grid)
    {
    	$grid->tools(function (Grid\Tools $tools) {
		    $tools->append(new WithdrawExportTool());
		    $tools->append(new WithdrawImportTool());
	    });
    }

	protected function gridFilter(Grid $grid)
	{
		$grid->filter(function (Grid\Filter $filter) {

			$filter->expand();

			$filter->scope('pending', '待处理')->where('status', 'pending');
			$filter->scope('confirmed', '已审核')->where('status', 'confirmed');
			$filter->scope('paid', '已到账')->where('status', 'paid');
			$filter->scope('failed', '已失败')->where('status', 'failed');
			$filter->scope('refusal', '已拒绝')->where('status', 'refusal');
			$filter->scope('returned', '已回退')->where('status', 'returned');

			$filter->column(1/2, function (Grid\Filter $filter) {
				$filter->disableIdFilter();
				$filter->equal('user_id', '会员 ID 查询');
			});
		});
	}

    protected function gridActions(Grid $grid)
    {
    	$grid->batchActions(function (Grid\Tools\BatchActions $batch) {
    		$batch->disableDelete();
    		$batch->add(new BatchConfirm());
    		$batch->add(new BatchRefuse());
	    });
	    $grid->actions(function (Grid\Displayers\Actions $actions) {
	    	$actions->disableDelete();
	    	$actions->disableView();
	    	$actions->add(new ConfirmWithdraw());
	    	$actions->add(new RefuseWithdraw());
	    	$actions->add(new ReturnFailedWithdraw());
	    });
    }

    public function edit($id, Content $content)
    {
	    return $content
		    ->title($this->title())
		    ->description($this->description['edit'] ?? trans('admin.edit'))
		    ->body($this->form($id)->edit($id));
    }

	protected function form($id = null)
    {
    	$withdraw = $this->withdraw($id);

        $form = new Form(new Withdraw());

        $form->display('user.name', '会员');
        $form->display('number', '提现单号');
        $form->display('target_amount', '提现金额');
        $form->display('charge_type', '手续费扣费方式')->with(function ($value) {
        	return config("site.withdraw.charge_types.$value");
        });
        $form->display('charge_amount', '手续费');
        $form->display('actual_amount', '到账金额');
        $form->display('method', '提现方式')->with(function ($value) {
        	return config("site.withdraw.methods.$value");
        });
        $form->textarea('remark', '备注');
        $form->textarea('info', '打款信息');

        if ($withdraw and $withdraw->status != 'pending') {
	        $form->display('status', '提现状态');
        } else {
	        $form->radio('status', '提现状态')->options([
	        	'refusal' => '拒绝提现',
		        'confirmed' => '审核通过'
	        ]);
        }

        $this->formTools($form);
        $this->formFooter($form, $id);
        $this->formSaving($form);
        $this->formSaved($form);

        return $form;
    }

	protected function formTools(Form $form)
	{
		$form->tools(function (Form\Tools $tools) {
			$tools->disableDelete();
		});
	}

    protected function formFooter(Form $form, $id = null)
    {
    	$form->footer(function (Form\Footer $footer) use ($id) {

    		if ($withdraw = Withdraw::find($id)) {
    			if ($withdraw->status != 'pending') {
    				$footer->disableSubmit();
    			}
		    }

    		$footer->disableReset();
    		$footer->disableViewCheck();
    		$footer->disableCreatingCheck();
    		$footer->disableEditingCheck();
	    });
    }

    protected function formSaving(Form $form)
    {
	    $form->saving(function (Form $form) {

	    	$originalStatus = $form->model()->getOriginal('status');

		    Log::debug("withdraw original status: {$originalStatus}");
		    Log::debug("withdraw current status: {$form->status}");

		    $status = $originalStatus;

		    if ($originalStatus === 'pending' and $form->status === 'refusal') {
			    $status = 'refusal';
		    }
		    if ($originalStatus === 'pending' and $form->status === 'confirmed') {
			    $status = 'confirmed';
		    }

		    $form->status = $status;
	    });
    }

    protected function formSaved(Form $form)
    {
	    $form->saved(function (Form $form) {
	    	$withdraw = $form->model();
		    if ($withdraw->status === 'refusal') {
			    app(RefuseGoldCoinWithdraw::class, [
			    	'withdraw' => $form->model()
			    ])->refuse();
		    }
		    if ($withdraw->status === 'confirmed') {
			    app(ApproveGoldCoinWithdraw::class, [
			    	'withdraw' => $form->model()
			    ])->approve();
		    }
	    });
    }

    public function export()
    {
    	if (Withdraw::query()->where('method','mybank')->doesntExist()) {
    		admin_toastr('无待网商银行提现数据', 'error');
    		return redirect()->back();
	    }
    	$time = Carbon::now()->toDateTimeString();
	    $obj = new MyBankWithdrawExport();
	  	return Excel::download($obj, '网商银行提现数据'.$time.'.xls');
    	/*$zlbData = new MyBankWithdrawExport();
		$zlbData->XzbExport();*/
    }

    public function postback(Content $content)
	{
		return $content->header('网商银行提现批量回传')
			->body(view('admin.withdraws.postback'));
	}

    public function import(Request $request)
    {

	    $file = request('withdraws');
	    if (!$file) {
		    admin_toastr('请输入导入内容', 'error');
		    return redirect()->back();
	    }
	    $file = explode("\r\n",$file);
	    foreach($file as $k=>$v){
	    	$v = str_replace("\t","___",$v);
	    	$arr = explode('___',$v);
	    	$file[$k] = $arr;

	    }
		$WithdrawImport = new WithdrawImport();
	   	$WithdrawImport->query($file);
	    admin_toastr('导入待发货订单已提交', 'success');
	    return redirect('admin/withdraws');
    }

}
